package com.hly.musicbackground.model.music.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hly.musicbackground.Enum.SongEnum;
import com.hly.musicbackground.Utils.PathUtils;
import com.hly.musicbackground.domain.Song;
import com.hly.musicbackground.exception.BusinessException;
import com.hly.musicbackground.result.Code;
import lombok.RequiredArgsConstructor;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

//音乐服务器（搜素，下载，歌词mv）
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class MusicKUWOServiceImpl {

    private final PathUtils pathUtils;

    public HashMap<String, Object> search(String key, int page, int limit){
        //接口请求响应
        String ww = "https://www.wx992.com/api/music/search3?key=" + key + "&pn=" + page + "&rn=" + limit;
//        String ww = "http://www.kuwo.cn/api/www/search/searchMusicBykeyWord?key=" + key + "&pn=" + page + "&rn=" + limit + "&httpsStatus=1&reqId=2a99ef20-98fa-11ec-a796-f9a683db6d09";
        String str = "";
        try {
            str = Jsoup.connect(ww).ignoreContentType(true).get().text();
        }catch (Exception e){
            e.printStackTrace();
        }


//        String data = JSON.parseObject(str).getString("data");
        String list = JSON.parseObject(str).getString("abslist");
//
        HashMap<String, Object> map = new HashMap<>();

        ArrayList<Song> songs = new ArrayList<>();

        map.put("list", songs);

//        //封装音乐实体集合
        try {
//            map.put("list", JSON.parseArray(list, Song.class));
            JSONArray objects = JSON.parseArray(list);
            for (Object object : objects) {
                JSONObject item = JSON.parseObject(JSON.toJSONString(object));
                Song build = Song.builder()
                        .rid(item.getInteger("DC_TARGETID"))
                        .name(item.getString("NAME"))
                        .artist(item.getString("ARTIST"))
                        .pic("https://img1.kuwo.cn/star/albumcover/" + item.getString("web_albumpic_short"))
                        .build();
                songs.add(build);
            }
        }catch (Exception e){
            e.printStackTrace();
            Code.BUSINESS_ERR("搜索结果解析失败");
        }
        Integer total = JSON.parseObject(str).getInteger("TOTAL");
        //返回音乐集合
        map.put("total", total);
        return map;
    }

    public String getMp3(String rid) {
        //接口
        String url = "https://www.wx992.com/api/music/3086c95b/" + rid;
        try {
            url = Jsoup.connect(url).ignoreContentType(true).get().text();
        }catch (Exception e){
            Code.BUSINESS_ERR("播放失败");
        }
        url = JSON.parseObject(url).getString("data");
        url = JSON.parseObject(url).getString("url");
        return url;
    }

    public String down(String rid, SongEnum type) {
        String url1 = "";
        String url4 = "";
        if (type.equals(SongEnum.MP3)){
            url1 = getMp3(rid);
            url4 = pathUtils.filePath + "\\" + rid + "mp3.mp3";
        }else {
            url1 = getMp3(rid);
            url4 = pathUtils.filePath + "\\" + rid + "mp4.mp4";
        }
        try {
            URL url2 = new URL(url1);
            int mes = 0;
            InputStream is = url2.openStream();
            OutputStream os = new FileOutputStream(pathUtils.path + url4);
            Boolean mes2 = true;
            int mes3 = 0;
            byte[] a = new byte[1024];

            while (mes2) {
                int n = is.read(a);
                if (n == -1) {
                    os.close();
                    is.close();
                    mes3 = 1;
                    mes = 1;
                }
                if (mes3 == 0) {
                    os.write(a, 0, n);
                } else {
                    mes2 = false;
                }

            }
        }catch (Exception e){
            e.printStackTrace();
            throw new BusinessException(Code.BUSINESS_ERR, "暂无资源");
        }
        return pathUtils.resourcesPath + url4.replace("\\", "/");
    }

    public String getLrc(String rid){
        String url = "https://m.kuwo.cn/newh5/singles/songinfoandlrc?musicId="+rid;
        try {
            url = Jsoup.connect(url).ignoreContentType(true).get().text();
        }catch (Exception e){
            e.printStackTrace();
        }
        String data =JSON.parseObject(url).getString("data");
        String lrclist=JSON.parseObject(data).getString("lrclist");
        return  lrclist;
    }

    public String getMp4(String rid) {
        String wz ="https://www.kuwo.cn/api/v1/www/music/playUrl?mid="+rid+"&type=mv";
        try {
            wz = Jsoup.connect(wz).ignoreContentType(true).get().text();
        }catch (Exception e){
            e.printStackTrace();
        }
        String data = JSON.parseObject(wz).getString("data");
        String mp4 = JSON.parseObject(data).getString("url");
        return mp4;
    }
}
